<?php

namespace Xtsb\Cims\Area;

class Area
{
  private static $citys;
  private static $countys;

  /**
   * 省市区信息
   * @return mixed
   */
  private static function area()
  {
    $area = file_get_contents(__DIR__ . '/area.json');
    return json_decode($area, true);
  }

  /**
   * 省
   * @return array
   */
  public static function province()
  {
    return array_column(self::area(), 'value');
  }

  /**
   * $province所属城市
   * @param $province
   * @return array
   */
  public static function city($province)
  {
    if (!$province) {
      return [];
    }

    self::$citys = array_column(self::area(), 'childs', 'value');

    return array_column(self::$citys[$province], 'value');
  }

  /**
   * 区县
   * @param $province
   * @return array
   */
  public static function county($province, $city)
  {
    if (!$province || !$city) {
      return [];
    }

    self::$citys = array_column(self::area(), 'childs', 'value');

    self::$countys = array_column(self::$citys[$province], 'childs', 'value');

    return array_column(self::$countys[$city], 'value');
  }

  /**
   * 查找 省市区
   * @param $name
   * @param string $type
   * @param null $province
   * @param null $city
   * @return bool|array
   */
  public static function areaSearch($name, $type = 'province', $province = null, $city = null): bool|array
  {
    switch ($type) {
      case 'province':
        $res = array_fuzzy_search($name, self::province());
        break;
      case 'city':
        $res = array_fuzzy_search($name, self::city($province));
        break;
      case 'county':
        $res = array_fuzzy_search($name, self::county($province, $city));
        break;
      default:
        $res = false;
        break;
    }
    return $res;
  }
}